package com.atguigu.srb.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

import java.util.ArrayList;

/**
 * 跨域配置
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(false); //是否允许携带cookie
        config.addAllowedOrigin("*"); //可接受的域，是一个具体域名或者*（代表任意域名）
        config.addAllowedHeader("*"); //允许携带的头
        config.addAllowedMethod("*"); //允许访问的方式
        //config.addAllowedOriginPattern("*");
        //ArrayList<String> allowedOriginPatterns = new ArrayList<>();
        //allowedOriginPatterns.add("*");
        //config.setAllowedOriginPatterns(allowedOriginPatterns);
        //config.addAllowedMethod("GET");
        //config.addAllowedMethod("POST");
        //config.addAllowedMethod("PUT");
        //config.addAllowedMethod("DELETE");
        //config.addAllowedMethod("PATCH");
        //config.addAllowedMethod("HEAD");
        //config.addAllowedMethod("OPTIONS");

        // 基于url的跨域策略
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}
